const express = require('express');
const cors = require('cors');
require('dotenv').config();
const { logger } = require('./src/utils/logger');

const app = express();
const PORT = process.env.PORT || 3000;

// 基本中间件
app.use(cors({
  origin: [
    'https://cumrbull.com',
    'https://api.cumrbull.com',
    'http://localhost:3001',
    'http://localhost:3002'
  ],
  credentials: true
}));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 健康检查端点
app.get('/health', (req, res) => {
  res.json({
    status: 'OK',
    message: 'CU MR BULL API Server is running',
    timestamp: new Date().toISOString(),
    environment: process.env.NODE_ENV || 'development'
  });
});

// API信息端点
app.get('/api', (req, res) => {
  res.json({
    name: 'CU MR BULL API',
    version: '1.0.0',
    description: '韩式餐厅管理系统API',
    endpoints: {
      health: '/health',
      auth: '/api/auth',
      admin: '/api/admin'
    },
    status: 'running',
    timestamp: new Date().toISOString()
  });
});

// 管理员登录端点（临时测试版本）
app.post('/api/auth/login', (req, res) => {
  const { email, password } = req.body;
  
  // 临时测试账户
  const testAccounts = {
    'admin@example.com': { password: '123456', role: 'admin', name: '系统管理员' },
    'manager@example.com': { password: '123456', role: 'manager', name: '餐厅经理' }
  };
  
  const account = testAccounts[email];
  
  if (!account || account.password !== password) {
    return res.status(401).json({
      success: false,
      message: '邮箱或密码错误'
    });
  }
  
  // 模拟JWT token
  const token = `mock_token_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  
  res.json({
    success: true,
    message: '登录成功',
    data: {
      token,
      user: {
        id: 1,
        email: account.email || email,
        name: account.name,
        role: account.role
      }
    }
  });
});

// 用户信息端点
app.get('/api/auth/me', (req, res) => {
  const authHeader = req.headers.authorization;
  
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({
      success: false,
      message: '未提供访问令牌'
    });
  }
  
  res.json({
    success: true,
    data: {
      id: 1,
      email: 'admin@example.com',
      name: '系统管理员',
      role: 'admin'
    }
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.originalUrl
  });
});

// 错误处理
app.use((error, req, res, next) => {
  logger.error('Server Error:', error);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? error.message : undefined
  });
});

// 启动服务器
app.listen(PORT, () => {
  logger.info(`🚀 CU MR BULL Production API Server 启动成功!`);
  logger.info(`📍 服务器地址: http://localhost:${PORT}`);
  logger.info(`🌍 环境: ${process.env.NODE_ENV || 'production'}`);
  logger.info(`📊 API文档: http://localhost:${PORT}/api`);
  logger.info(`💚 健康检查: http://localhost:${PORT}/health`);
  logger.info(`⏰ 启动时间: ${new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Singapore' })}`);
});

// 未捕获异常与未处理 Promise 拒绝
process.on('unhandledRejection', (reason) => {
  logger.error('Unhandled Rejection:', reason);
  if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') process.exit(1);
});

process.on('uncaughtException', (err) => {
  logger.error('Uncaught Exception:', err);
  if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') process.exit(1);
});

module.exports = app;